/**
 * 日志中间件
 * 作者：GodMainCode
 * 创建时间：2024-01-17
 * 修改时间：2024-01-17
 * 修改人：GodMainCode
 */

import { Injectable, NestMiddleware, Logger } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { LogService } from '../../modules/log/log.service';
import { LogType, LogLevel } from '../../interfaces/log.interface';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  private readonly logger = new Logger('HTTP');

  constructor(private readonly logService: LogService) {}

  use(request: Request, response: Response, next: NextFunction): void {
    const { ip, method, originalUrl: url } = request;
    const userAgent = request.get('user-agent') || '';
    const startTime = Date.now();

    response.on('finish', () => {
      const { statusCode } = response;
      const contentLength = response.get('content-length');
      const duration = Date.now() - startTime;

      // 控制台日志
      this.logger.log(
        `${method} ${url} ${statusCode} ${contentLength}b - ${userAgent} ${ip} - ${duration}ms`,
      );

      // 数据库日志
      this.logService.create(
        LogType.OPERATION,
        statusCode >= 400 ? LogLevel.ERROR : LogLevel.INFO,
        request,
        duration,
        contentLength,
        statusCode >= 400 ? response.statusMessage : undefined,
      ).catch(err => {
        this.logger.error('Failed to save log', err);
      });
    });

    next();
  }
} 